package com.mcr.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mcr.reggie.dao.AddressBookMapper;
import com.mcr.reggie.entity.AddressBook;
import com.mcr.reggie.service.AddressBookService;
import com.mcr.reggie.utils.BaseContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Override
    public void saveAddressBook(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getUser());
        addressBookMapper.insert(addressBook);
    }

    @Override
    public void setDefaultAddressBook(AddressBook addressBook) {
        LambdaUpdateWrapper<AddressBook> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(AddressBook::getUserId, BaseContext.getUser())
               .eq(AddressBook::getIsDefault,1)
               .set(AddressBook::getIsDefault, 0);
        //SQL:update address_book set is_default = 0 where user_id = ? and is_default =1
        this.update(wrapper);
        addressBook.setIsDefault(1);
        //SQL:update address_book set is_default = 1 where id = ?
        this.updateById(addressBook);
    }

    @Override
    public AddressBook getAddressBookById(Long id) {
        AddressBook addressBook = addressBookMapper.selectById(id);
        return addressBook;
    }

    @Override
    public AddressBook getDefaultAddressBook() {
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId, BaseContext.getUser())
                    .eq(AddressBook::getIsDefault, 1);
        //SQL:select * from address_book where user_id = ? and is_default = 1
        AddressBook addressBook = addressBookMapper.selectOne(queryWrapper);
        return addressBook;
    }

    @Override
    public List<AddressBook> listAddressBook() {
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq( AddressBook::getUserId, BaseContext.getUser())
                    .orderByDesc(AddressBook::getUpdateTime);
        //SQL:select * from address_book where user_id = ? order by update_time desc
        List<AddressBook> addressBookList = addressBookMapper.selectList(queryWrapper);
        return addressBookList;
    }
}
